package Captcha

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"encoding/json"
	"github.com/mojocn/base64Captcha"
	"log"
)

//ConfigJsonBody json request body.
type ConfigJsonBody struct {
	//验证码信息
	Id              string
	CaptchaType     string
	VerifyValue     string
	ConfigAudio     base64Captcha.ConfigAudio
	ConfigCharacter base64Captcha.ConfigCharacter
	ConfigDigit     base64Captcha.ConfigDigit
}

type Captcha struct {
	controllers.MainController
}

func (this *Captcha) GetCaptcha() {
	//parse request parameters
	//接收客户端发送来的请求参数
	r := this.Ctx.Request
	decoder := json.NewDecoder(r.Body)
	var postParameters ConfigJsonBody
	err := decoder.Decode(&postParameters)
	if err != nil {
		log.Println(err)
	}
	defer r.Body.Close()
	//create base64 encoding captcha
	//创建base64图像验证码
	var config interface{}
	switch postParameters.CaptchaType {
	case "audio":
		config = postParameters.ConfigAudio
	case "character":
		config = postParameters.ConfigCharacter
	default:
		config = postParameters.ConfigDigit
	}
	//GenerateCaptcha 第一个参数为空字符串,包会自动在服务器一个随机种子给你产生随机uiid.
	captchaId, digitCap := base64Captcha.GenerateCaptcha(postParameters.Id, config)
	base64Png := base64Captcha.CaptchaWriteToBase64Encoding(digitCap)
	//fmt.Println(captchaId)
	//fmt.Println(base64Png)

	//or you can do this
	//你也可以是用默认参数 生成图像验证码

	//set json response
	//设置json响应
	this.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
	body := map[string]interface{}{"code": 200, "data": base64Png, "captchaId": captchaId, "msg": "success"}
	this.Data["json"] = body
	this.ServeJSON()
}
